import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';
import '../models/service_item.dart';
import '../services/legacy_compatibility.dart';
import '../services/app_services.dart';
import '../config/app_config.dart';
import '../config/local_config_manager.dart';
import 'edit_service_dialog.dart';

class ServiceItemWidget extends StatefulWidget {
  final ServiceItem service;
  final Function(bool) onToggle;
  final VoidCallback onUpgradeRequired;
  final bool Function() canEnableMoreServices;
  final bool isLoading;
  final Function(ServiceItem)? onEdit;
  final Function(ServiceItem)? onDelete;
  final VoidCallback? onRefresh;

  const ServiceItemWidget({
    Key? key,
    required this.service,
    required this.onToggle,
    required this.onUpgradeRequired,
    required this.canEnableMoreServices,
    this.isLoading = false,
    this.onEdit,
    this.onDelete,
    this.onRefresh,
  }) : super(key: key);

  @override
  State<ServiceItemWidget> createState() => _ServiceItemWidgetState();
}

// 连接状态枚举
enum ConnectionStatus { disconnected, connecting, connected, error }

class _ServiceItemWidgetState extends State<ServiceItemWidget> with LocalConfigAwareMixin {
  // 连接状态
  ConnectionStatus _connectionStatus = ConnectionStatus.disconnected;

  // 返回的域名
  String? _connectedDomain;

  @override
  void initState() {
    super.initState();
    _initializeConnectionState();
  }

  @override
  void didUpdateWidget(ServiceItemWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('🔄 didUpdateWidget: ${widget.service.name} - 旧status: ${oldWidget.service.status}, 新status: ${widget.service.status}, 当前连接状态: $_connectionStatus');
    
    // 只有在服务状态实际发生变化时才检查连接状态，避免不必要的状态更新
    if (oldWidget.service.status != widget.service.status ||
        oldWidget.service.tunnelId != widget.service.tunnelId) {
      print('🔄 服务状态或tunnelId发生变化，检查连接状态');
      _checkConnectionStateAsync();
    }
  }

  /// 异步检查连接状态
  void _checkConnectionStateAsync() async {
    // 检查真实的TCP连接状态（包括持久化状态）
    final appService = AppService();
    final hasActiveTcpConnection = await appService.isTunnelConnectedPersistent(widget.service.tunnelId ?? '');
    
    // 如果组件已经销毁，不要更新状态
    if (!mounted) return;
    
    // 如果有活跃的TCP连接，保持连接状态
    if (hasActiveTcpConnection) {
      print('🔄 检测到活跃TCP连接，保持连接状态 - ${widget.service.name}');
      if (_connectionStatus != ConnectionStatus.connected) {
        setState(() {
          _connectionStatus = ConnectionStatus.connected;
        });
      }
      return;
    }
    
    // 强化状态保护：如果当前正在连接中或已连接，且刚刚发生了状态变化（比如用户刚点击连接），
    // 不要被外部状态重置，给TCP连接建立一些时间
    if (_connectionStatus == ConnectionStatus.connecting) {
      print('🔄 正在连接中，不被外部重置 - ${widget.service.name}');
      return;
    }
    
    // 如果当前已连接，检查是否是最近连接的（给一些缓冲时间）
    if (_connectionStatus == ConnectionStatus.connected) {
      // 通过重新检查持久化状态来确认连接
      final stillConnected = await appService.isTunnelConnectedPersistent(widget.service.tunnelId ?? '');
      if (stillConnected) {
        print('🔄 二次确认持久化连接，保持连接状态 - ${widget.service.name}');
        return;
      }
      print('🔄 持久化连接已失效，允许状态重置 - ${widget.service.name}');
    }
    
    // 只有在确认没有任何连接迹象时，才根据服务状态重新初始化
    print('🔄 重新初始化连接状态 - ${widget.service.name}');
    _initializeConnectionState();
  }

  void _initializeConnectionState() {
    // 异步检查连接状态（包括持久化状态）
    _initializeConnectionStateAsync();
  }

  void _initializeConnectionStateAsync() async {
    // 🔥🔥🔥 关键修复：只信任本地TCP连接状态和持久化状态
    // 
    // 问题场景：
    // 1. 用户点击断开连接
    // 2. Go层TCP连接断开，持久化状态清除
    // 3. 服务端数据库status更新是异步的（Future.microtask）
    // 4. 用户立即点击刷新，服务端返回的status可能仍是'active'
    // 5. 如果依赖status来初始化UI，会导致显示为已连接（错误）
    // 
    // 解决方案：
    // 1. 只检查本地的TCP连接状态（isTunnelConnectedPersistent）
    // 2. 不依赖服务端的status字段来初始化连接状态
    // 3. status字段只用于后端业务逻辑，不用于UI展示
    
    final appService = AppService();
    final hasActiveTcpConnection = await appService.isTunnelConnectedPersistent(widget.service.tunnelId ?? '');
    
    // 如果组件已经销毁，不要更新状态
    if (!mounted) return;
    
    if (hasActiveTcpConnection) {
      // 有活跃的TCP连接，显示为已连接
      setState(() {
        _connectionStatus = ConnectionStatus.connected;
        _connectedDomain = widget.service.customDomain;
      });
      print('🔄 初始化：检测到活跃TCP连接 - ${widget.service.name}');
    } else {
      // 没有活跃的TCP连接，显示为断开状态
      setState(() {
        _connectionStatus = ConnectionStatus.disconnected;
        _connectedDomain = null;
      });
      print('🔄 初始化：显示为断开状态 - ${widget.service.name}');
    }
  }

  Future<void> _connectToServer() async {
    print('🔵 开始连接服务: ${widget.service.name} (${widget.service.ip}:${widget.service.port})');
    
    // 立即更新UI为连接中状态
    if (!mounted) return;
    setState(() {
      _connectionStatus = ConnectionStatus.connecting;
    });

    // 使用 addPostFrameCallback 确保在当前帧渲染完成后才执行连接操作
    // 这样可以保证 CircularProgressIndicator 的动画能够启动
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      
      // 再等待一帧，确保动画完全启动
      Future.delayed(const Duration(milliseconds: 100), () async {
        if (!mounted) return;
        
        try {
          print('🔵 调用AppService.createAndConnectTunnel...');
          final appService = AppService();
          
          // 添加30秒超时机制，防止长时间卡在连接状态
          final tunnel = await appService.createAndConnectTunnel(
            localPort: widget.service.port.toString(),
            localHost: widget.service.ip,
            serverName: widget.service.name,
          ).timeout(
            const Duration(seconds: 30),
            onTimeout: () {
              throw Exception('连接超时，请检查网络连接和服务器状态');
            },
          );

          print('🟢 隧道创建成功: ${tunnel.publicAddress}');
          
          // 确保在UI线程中更新状态
          if (mounted) {
            setState(() {
              _connectionStatus = ConnectionStatus.connected;
              _connectedDomain = tunnel.publicAddress;
            });

            // 调用父组件的刷新方法以更新服务列表
            widget.onToggle(true);
            print('🟢 状态已更新为已连接');
          }

          // 不需要立即刷新整个列表，因为TunnelProvider已经更新了本地状态
        } catch (e) {
          print('🔴 连接失败: $e');
          
          // 确保在UI线程中更新状态
          if (mounted) {
            setState(() {
              _connectionStatus = ConnectionStatus.error;
            });
            
            // 2秒后重置为断开状态
            Future.delayed(const Duration(seconds: 2), () {
              if (mounted) {
                setState(() {
                  _connectionStatus = ConnectionStatus.disconnected;
                });
              }
            });
          }
        }
      });
    });
  }

  Future<void> _disconnectFromServer() async {
    print('🔴 开始断开连接: ${widget.service.name}');
    
    // 显示断开中状态
    if (!mounted) return;
    setState(() {
      _connectionStatus = ConnectionStatus.connecting;
    });
    
    // 使用 addPostFrameCallback 确保在当前帧渲染完成后才执行断开操作
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!mounted) return;
      
      Future.delayed(const Duration(milliseconds: 100), () async {
        if (!mounted) return;
        
        try {
          final appService = AppService();
          // 🔥 关键修复：使用tunnelId而不是service.id
          // service.id是数据库ID，tunnelId是Go层的隧道UUID
          final tunnelId = widget.service.tunnelId;
          if (tunnelId == null || tunnelId.isEmpty) {
            throw Exception('隧道ID为空，无法断开连接');
          }
          await appService.disconnectTunnel(tunnelId);

          // 确保在UI线程中更新状态
          if (mounted) {
            setState(() {
              _connectionStatus = ConnectionStatus.disconnected;
              _connectedDomain = null;
            });

            widget.onToggle(false);
            print('🔴 隧道已断开');
          }

          // 不需要立即刷新整个列表
        } catch (e) {
          print('🔴 断开连接失败: $e');
          
          // 确保在UI线程中更新状态
          if (mounted) {
            setState(() {
              _connectionStatus = ConnectionStatus.error;
            });
            
            // 2秒后重置为断开状态
            Future.delayed(const Duration(seconds: 2), () {
              if (mounted) {
                setState(() {
                  _connectionStatus = ConnectionStatus.disconnected;
                });
              }
            });
          }
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final screenWidth = MediaQuery.of(context).size.width;
    
    // 响应式设计：根据屏幕宽度调整布局
    final isMobile = screenWidth < 600; // 小于600px视为移动端
    final isTablet = screenWidth >= 600 && screenWidth < 900; // 600-900px为平板
    
    // 根据设备类型调整间距
    final horizontalMargin = isMobile ? 12.0 : 16.0;
    final horizontalPadding = isMobile ? 12.0 : 16.0;
    final verticalPadding = isMobile ? 8.0 : 10.0;
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: horizontalMargin, vertical: 4),
      decoration: BoxDecoration(
        color: theme.colorScheme.surface,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(
          color: theme.colorScheme.outline.withValues(alpha: 0.2),
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          // 服务信息区域（标题栏）
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(
              horizontal: horizontalPadding, 
              vertical: verticalPadding,
            ),
            decoration: BoxDecoration(
              color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3),
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
            ),
            child: isMobile 
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 移动端：服务名称和协议标签垂直排列
                    Row(
                      children: [
                        Expanded(
                          child: Text(
                            widget.service.name,
                            style: theme.textTheme.titleMedium?.copyWith(
                              fontWeight: FontWeight.bold,
                              color: theme.colorScheme.onSurface,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        const SizedBox(width: 8),
                        // 协议标签
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: 6,
                            vertical: 3,
                          ),
                          decoration: BoxDecoration(
                            color: widget.service.protocol == 'tcp' 
                                ? Colors.orange.withValues(alpha: 0.15)
                                : Colors.blue.withValues(alpha: 0.15),
                            borderRadius: BorderRadius.circular(6),
                            border: Border.all(
                              color: widget.service.protocol == 'tcp' 
                                  ? Colors.orange.withValues(alpha: 0.3)
                                  : Colors.blue.withValues(alpha: 0.3),
                              width: 1,
                            ),
                          ),
                          child: Text(
                            widget.service.protocol.toUpperCase(),
                            style: theme.textTheme.labelSmall?.copyWith(
                              color: widget.service.protocol == 'tcp' 
                                  ? Colors.orange[700]
                                  : Colors.blue[700],
                              fontWeight: FontWeight.w600,
                              letterSpacing: 0.5,
                              fontSize: 9,
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 8),
                    // 连接开关单独一行
                    _buildConnectionButton(),
                  ],
                )
              : Row(
                  children: [
                    Expanded(
                      child: Row(
                        children: [
                          // 服务名称
                          Flexible(
                            child: Text(
                              widget.service.name,
                              style: theme.textTheme.titleMedium?.copyWith(
                                fontWeight: FontWeight.bold,
                                color: theme.colorScheme.onSurface,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          const SizedBox(width: 10),
                          // 协议标签
                          Container(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 8,
                              vertical: 4,
                            ),
                            decoration: BoxDecoration(
                              color: widget.service.protocol == 'tcp' 
                                  ? Colors.orange.withValues(alpha: 0.15)
                                  : Colors.blue.withValues(alpha: 0.15),
                              borderRadius: BorderRadius.circular(6),
                              border: Border.all(
                                color: widget.service.protocol == 'tcp' 
                                    ? Colors.orange.withValues(alpha: 0.3)
                                    : Colors.blue.withValues(alpha: 0.3),
                                width: 1,
                              ),
                            ),
                            child: Text(
                              widget.service.protocol.toUpperCase(),
                              style: theme.textTheme.labelSmall?.copyWith(
                                color: widget.service.protocol == 'tcp' 
                                    ? Colors.orange[700]
                                    : Colors.blue[700],
                                fontWeight: FontWeight.w600,
                                letterSpacing: 0.5,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(width: 12),
                    _buildConnectionButton(),
                  ],
                ),
          ),
          
          // 详细信息区域
          Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(
              horizontal: horizontalPadding, 
              vertical: verticalPadding,
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 内网地址
                Row(
                  children: [
                    Container(
                      padding: EdgeInsets.all(isMobile ? 4 : 5),
                      decoration: BoxDecoration(
                        color: Colors.grey.withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(6),
                      ),
                      child: Icon(
                        Icons.computer,
                        size: isMobile ? 14 : 16,
                        color: Colors.grey[700],
                      ),
                    ),
                    SizedBox(width: isMobile ? 6 : 8),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '本地地址',
                            style: theme.textTheme.labelSmall?.copyWith(
                              color: theme.colorScheme.onSurface.withValues(alpha: 0.6),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          const SizedBox(height: 2),
                          Text(
                            '${widget.service.ip}:${widget.service.port}',
                            style: theme.textTheme.bodyMedium?.copyWith(
                              color: theme.colorScheme.onSurface,
                              fontFamily: 'monospace',
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                
                // 隧道地址
                if (_getDisplayUrl() != null) ...[
                  SizedBox(height: isMobile ? 8 : 10),
                  Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: isMobile ? 8 : 10, 
                      vertical: isMobile ? 6 : 8,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.blue.withValues(alpha: 0.05),
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(
                        color: Colors.blue.withValues(alpha: 0.2),
                        width: 1,
                      ),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.public,
                          size: isMobile ? 14 : 16,
                          color: Colors.blue[600],
                        ),
                        SizedBox(width: isMobile ? 6 : 8),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SelectableText(
                                '公网地址',
                                style: theme.textTheme.labelSmall?.copyWith(
                                  color: Colors.blue[700],
                                  fontWeight: FontWeight.w500,
                                  fontSize: isMobile ? 10 : null,
                                ),
                              ),
                              const SizedBox(height: 2),
                              GestureDetector(
                                onTap: () {
                                  Clipboard.setData(ClipboardData(text: _getDisplayUrl()!));
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: const Text('✓ 隧道地址已复制到剪贴板'),
                                      duration: const Duration(seconds: 2),
                                      backgroundColor: Colors.green[600],
                                    ),
                                  );
                                },
                                child: Text(
                                  _getDisplayUrl()!,
                                  style: theme.textTheme.bodyMedium?.copyWith(
                                    color: Colors.blue[700],
                                    decoration: TextDecoration.underline,
                                    fontWeight: FontWeight.w600,
                                    fontSize: isMobile ? 12 : null,
                                  ),
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: isMobile ? 6 : 8),
                        InkWell(
                          onTap: () {
                            Clipboard.setData(ClipboardData(text: _getDisplayUrl()!));
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: const Text('✓ 隧道地址已复制到剪贴板'),
                                duration: const Duration(seconds: 2),
                                backgroundColor: Colors.green[600],
                              ),
                            );
                          },
                          borderRadius: BorderRadius.circular(4),
                          child: Padding(
                            padding: EdgeInsets.all(isMobile ? 6 : 4),
                            child: Icon(
                              Icons.copy,
                              size: isMobile ? 18 : 16,
                              color: Colors.blue[600],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ],
            ),
          ),
          
          // 分隔线
          Divider(
            height: 1,
            thickness: 1,
            color: theme.colorScheme.outline.withValues(alpha: 0.15),
          ),
          
          // 操作按钮
          Container(
            padding: EdgeInsets.symmetric(
              horizontal: isMobile ? 6 : 8, 
              vertical: isMobile ? 6 : 4,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                TextButton.icon(
                  onPressed: () => _showEditDialog(),
                  icon: Icon(Icons.edit, size: isMobile ? 16 : 14),
                  label: Text(
                    '编辑', 
                    style: TextStyle(fontSize: isMobile ? 14 : 13),
                  ),
                  style: TextButton.styleFrom(
                    foregroundColor: theme.colorScheme.primary,
                    padding: EdgeInsets.symmetric(
                      horizontal: isMobile ? 12 : 10, 
                      vertical: isMobile ? 8 : 6,
                    ),
                    minimumSize: Size(0, isMobile ? 40 : 32),
                  ),
                ),
                SizedBox(width: isMobile ? 6 : 4),
                TextButton.icon(
                  onPressed: () => widget.onDelete?.call(widget.service),
                  icon: Icon(Icons.delete_outline, size: isMobile ? 16 : 14),
                  label: Text(
                    '删除', 
                    style: TextStyle(fontSize: isMobile ? 14 : 13),
                  ),
                  style: TextButton.styleFrom(
                    foregroundColor: Colors.red[700],
                    padding: EdgeInsets.symmetric(
                      horizontal: isMobile ? 12 : 10, 
                      vertical: isMobile ? 8 : 6,
                    ),
                    minimumSize: Size(0, isMobile ? 40 : 32),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String? _getDisplayUrl() {
    // 优先显示连接后的URL，其次显示服务的customDomain
    if (_connectedDomain != null && _connectedDomain!.isNotEmpty) {
      return _connectedDomain;
    }
    if (widget.service.customDomain != null &&
        widget.service.customDomain!.isNotEmpty) {
      return widget.service.customDomain;
    }
    return null;
  }

  // 构建信息行
  Widget _buildInfoRow({
    required IconData icon,
    required Color iconColor,
    required String label,
    required String value,
    bool isClickable = false,
    VoidCallback? onTap,
  }) {
    Widget content = Row(
      children: [
        Icon(icon, size: 20, color: iconColor),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                label,
                style: TextStyle(
                  fontSize: 12,
                  color: Theme.of(
                    context,
                  ).colorScheme.onSurface.withValues(alpha: 0.6),
                  fontWeight: FontWeight.w500,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                value,
                style: TextStyle(
                  fontSize: 14,
                  color: isClickable
                      ? Theme.of(context).colorScheme.primary
                      : Theme.of(context).colorScheme.onSurface,
                  fontFamily: 'monospace',
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
        ),
      ],
    );

    if (isClickable && onTap != null) {
      return GestureDetector(
        onTap: onTap,
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 4),
          child: content,
        ),
      );
    }

    return content;
  }

  // 构建连接开关
  Widget _buildConnectionButton() {
    switch (_connectionStatus) {
      case ConnectionStatus.connecting:
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              width: 18,
              height: 18,
              child: CircularProgressIndicator(
                strokeWidth: 2.5,
                valueColor: AlwaysStoppedAnimation<Color>(
                  Theme.of(context).colorScheme.primary,
                ),
              ),
            ),
            const SizedBox(width: 10),
            Text(
              '连接中...',
              style: TextStyle(
                color: Theme.of(context).colorScheme.onSurface,
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        );
      case ConnectionStatus.error:
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error, color: Theme.of(context).colorScheme.error, size: 16),
            const SizedBox(width: 8),
            Text(
              '错误',
              style: TextStyle(
                color: Theme.of(context).colorScheme.error,
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        );
      default:
        return Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            SelectableText(
              _connectionStatus == ConnectionStatus.connected ? '已连接' : '未连接',
              style: TextStyle(
                color: Theme.of(context).colorScheme.onSurface,
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(width: 8),
            Switch(
              value: _connectionStatus == ConnectionStatus.connected,
              onChanged: _connectionStatus == ConnectionStatus.connecting 
                  ? null 
                  : (bool value) {
                      if (value) {
                        _connectToServer();
                      } else {
                        _disconnectFromServer();
                      }
                    },
              // 移除硬编码颜色，使用主题系统颜色
              // activeColor: Colors.green,
              // activeTrackColor: Colors.green.withValues(alpha: 0.5),
              // inactiveThumbColor: Colors.grey[300],
              // inactiveTrackColor: Colors.grey[600],
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
          ],
        );
    }
  }

  Color _getStatusColor() {
    switch (_connectionStatus) {
      case ConnectionStatus.connected:
        return Colors.green;
      case ConnectionStatus.connecting:
        return Colors.orange;
      case ConnectionStatus.error:
        return Colors.red;
      case ConnectionStatus.disconnected:
        return Colors.grey;
    }
  }

  // 显示编辑对话框
  void _showEditDialog() {
    final tunnelData = TunnelData(
      tunnelId: widget.service.tunnelId!,
      serverName: widget.service.name,
      localHost: widget.service.ip,
      localPort: widget.service.port.toString(),
      tunnelHost: AppConfig.instance.tcpTunnelHost,
      // 从配置获取隧道主机
      tunnelPort: AppConfig.instance.tcpTunnelPort.toString(),
      // 从配置获取隧道端口
      publicPort: '80',
      // 默认公网端口
      publicAddress: widget.service.customDomain ?? '',
      tunnelType: widget.service.protocol,
      isConnected: widget.service.isEnabled,
    );

    showDialog(
      context: context,
      builder: (context) => EditServiceDialog(tunnel: tunnelData),
    );
  }

  Widget _buildActionButton() {
    switch (_connectionStatus) {
      case ConnectionStatus.connecting:
        return const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(strokeWidth: 2),
        );
      case ConnectionStatus.connected:
        return IconButton(
          onPressed: _disconnectFromServer,
          icon: const Icon(Icons.stop, color: Colors.red),
          tooltip: '断开连接',
        );
      case ConnectionStatus.disconnected:
      case ConnectionStatus.error:
        return IconButton(
          onPressed: _connectToServer,
          icon: const Icon(Icons.play_arrow, color: Colors.green),
          tooltip: '开始连接',
        );
    }
  }
}